﻿using System;
using System.Collections.Generic;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Timers;

namespace vconf_server
{
    class VConfServerMain
    {
        static int Main(string[] args)
        {
            Console.Title = "VConf server";
            Console.WriteLine("[DEBUG] Starting server... ");

            RegisterTimers();
            
            // Opens passive or "listening" socket, 
            // or throws an exception
            TcpChannel chan = new TcpChannel(8084);

            // Lets the remoting system use the socket
            ChannelServices.RegisterChannel(chan, false);

            // Associate the class HelloServer with the URI "SayHello"
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(VConfServer),  //type
                "VConf",  //uri
                WellKnownObjectMode.Singleton); //mode
            //WellKnownObjectMode.Singleton);

            Console.WriteLine("[DEBUG] Server up and running");
            // Wait until user hits enter to close server
            System.Console.ReadLine();

            // Closes socket
            chan.StopListening(null);

            return 0;
        }

        static private void RegisterTimers()
        {
            Timer t = new Timer();
            t.Interval = 2000;
            t.Elapsed += new ElapsedEventHandler(ClearInactiveUsers);
            t.AutoReset = true;
            Console.WriteLine("[DEBUG] Timers registered");
            t.Start();
        }

        static void ClearInactiveUsers(object sender, ElapsedEventArgs e)
        {
            State.ClearInactiveUsers();
        }
    }
}
